package com.neusoft.weixin.service.account;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.common.util.UUIDGenerator;
import com.neusoft.common.util.WeixinConfigUtil;
import com.neusoft.weixin.entity.Menu;
import com.neusoft.weixin.pojo.AccessToken;
import com.neusoft.weixin.pojo.Button;
import com.neusoft.weixin.pojo.CommonButton;
import com.neusoft.weixin.pojo.ComplexButton;
import com.neusoft.weixin.pojo.CustomMenu;
import com.neusoft.weixin.repository.account.MenuDao;
import com.neusoft.weixin.utils.WeixinUtil;


/**
 * 菜单管理类.
 * 
 */
@Service(value = "menuService")
public class MenuService {


	private static Logger LOG = LoggerFactory.getLogger(MenuService.class);
	
	// 第三方用户唯一凭证  
	private static final String APPID = WeixinConfigUtil.getAppId();
	 // 第三方用户唯一凭证密钥  
	private static final String APPSECRET = WeixinConfigUtil.getAppSecret();
	
	private static final String PROXYHOST = WeixinConfigUtil.getProxyHost();
	
	private static final String PROXYPORT = WeixinConfigUtil.getProxyPort();

	@Autowired
	private MenuDao menuDao;
	
	
	public JSONArray getTreeData(){
		
		LOG.debug("加载菜单");
		List<Map<String,String>> data = menuDao.getTreeData();
		Map root = new HashMap();
		root.put("MENU_ID", "0"); 
		root.put("MENU_NAME", "weixin"); 
		root.put("MENU_LOCATION", ""); 
		root.put("PARENT_ID", ""); 
		root.put("MENU_DESC", ""); 
		root.put("isParent",true);
		root.put("open", Boolean.valueOf(true)); 
		data.add(root);
		
		return JSONArray.fromObject(data);
		
	}
	
	public JSONObject createCustomMenu(){
		
		//设置代理上外网
		if ( null != PROXYHOST && null != PROXYPORT ){
			System.getProperties().put("proxySet", "true");
			System.getProperties().put("proxyHost", "10.20.7.12");
			System.getProperties().put("proxyPort", "8088");
		}
        
        JSONObject json = new JSONObject();
     // 调用接口获取access_token  
        AccessToken at = WeixinUtil.getAccessToken(APPID, APPSECRET);  
  
        if (null != at) {  
            // 调用接口创建菜单  
            int result = WeixinUtil.createMenu(getMenu(), at.getToken());  
            
            
            // 判断菜单创建结果  
            if (0 == result){
            	String msg = "菜单创建成功！";
				LOG.info(msg);  
            	json.put("status", "1");
            	json.put("detail", msg);
            }
            else{
            	String errorMsg = "菜单创建失败，错误码：" + result;
				LOG.info(errorMsg);
				json.put("status", "-1");
            	json.put("detail", errorMsg);
            	
            }
        }  
		
		return json;
	}
	
	private CustomMenu getMenu(){
		
		List<Map<String,String>> mainMenu = menuDao.getMainMenu("0");
		List<Map<String,String>> subMenu = menuDao.getSubMenu("0");
		
		List<Button> mainButtons = new ArrayList<Button>();
		
		for ( int i = 0; i < mainMenu.size(); i++ ){
			Map<String,String> main = mainMenu.get(i);
			String menuId = main.get("MENU_ID");
			ComplexButton button = new ComplexButton();
			button.setName(main.get("MENU_NAME"));
			List<Button> subButtons = new ArrayList<Button>();
			
			for ( int j = 0; j < subMenu.size(); j++ ){
				Map<String,String> sub = subMenu.get(j);
				if ( sub.get("PARENT_ID").equals(menuId) ){
					CommonButton subButton = new CommonButton();
					subButton.setName(sub.get("MENU_NAME"));
					subButton.setKey(sub.get("MENU_NUM"));
					subButton.setType("click");
					subButtons.add(subButton);
				}
			}
			
			button.setSub_button(subButtons.toArray(new Button[subButtons.size()]));
			mainButtons.add(button);
		}
		
		
		CustomMenu customMenu = new CustomMenu();
		customMenu.setButton(mainButtons.toArray(new Button[mainButtons.size()]));
		
		return customMenu;
		
	}
	
	
	
	@Transactional(rollbackFor=Exception.class)
	public JSONObject addOrEditMenu(JSONObject job) throws Exception{
		String menuid = job.getString("MENU_ID");
		Menu menu = new Menu();
		if(menuid==null||menuid.isEmpty()){
			menuid = UUIDGenerator.getUUID();
			menu.setMenuId(menuid);
			menu.setParentId(job.getString("PARENT_ID"));
			menu.setMenuNum(job.getString("MENU_NUM"));
			menu.setMenuName(job.getString("MENU_NAME"));
			menu.setMenuLocation(job.getString("MENU_LOCATION"));
			menu.setMenuDesc(job.getString("MENU_DESC"));
			menu.setMenuType(job.getString("MENU_TYPE"));
			menuDao.insertMenu(menu);
			job.put("MENU_ID", menuid);
			job.put("status", "1");
			job.put("detail", "添加菜单成功!");
			if(job.getString("PARENT_ID").equals("0")){
				job.put("isParent",true);
			}else{
				job.put("isParent",false);
			}
			return job;
		}else{
			menu.setMenuId(menuid);
			menu.setMenuName(job.getString("MENU_NAME"));
			menu.setMenuLocation(job.getString("MENU_LOCATION"));
			menu.setMenuNum(job.getString("MENU_NUM"));
			menu.setMenuDesc(job.getString("MENU_DESC"));
			menu.setMenuType(job.getString("MENU_TYPE"));
			menuDao.updateMenu(menu);
			job.put("status", "1");
			job.put("detail", "编辑菜单成功!");
			if(job.getString("PARENT_ID").equals("0")){
				job.put("isParent",true);
			}else{
				job.put("isParent",false);
			}
			return job;
		}
	}
	
	public JSONObject deleteMenu(String menuid) throws Exception{
		
		menuDao.deleteMenu(menuid);
		JSONObject result = new JSONObject();
		result.put("status", "1");
		result.put("detail", "删除菜单成功");
		
		return result;
		
		
	}
	
	public List getTopMenu(String menuNum) throws Exception{
		List menus = null;
		if ( null != menuNum && "0".equals(menuNum) ){
			menus = menuDao.getTopMenu(menuNum);
		}else{
			menus = menuDao.getWeixinMenu(menuNum);
		}
		return menus;
		
	}
	
	
	public List getMenuMessage(String menuNum){
		return menuDao.getMenuMessage(menuNum);
	}
	
	

}
